package com.uzai.console.service.md.mdrebotcmd.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.enums.MdRobotCmdKeyEnum;
import com.uzai.common.enums.UzaiCmdKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.entity.MdRobotCmd;
import com.uzai.console.entity.RobotCmd;
import com.uzai.console.mapper.MdRobotCmdMapper;
import com.uzai.console.service.md.mdrebotcmd.MdRobotCmdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 免单指令
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class MdRobotCmdServiceImpl implements MdRobotCmdService {

    Logger logger = LoggerFactory.getLogger(MdRobotCmdServiceImpl.class);

    @Autowired
    private MdRobotCmdMapper mdRobotCmdMapper;

    /**
     * 保存免单指令
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param commandList
     * @return null
     */
    public void addMdRobotCmdForMdAtivity(Long merId, Long activityId, String robotCmdKey, List<String> commandList){
        //先删除活动唤醒指令
        mdRobotCmdMapper.deleteByKey(merId, activityId, robotCmdKey);
        //在保存活动唤醒指令
        saveRobotCmd(merId, activityId, robotCmdKey, commandList);
    }


    /**
     * 新增指令
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param commandList
     * @return null
     */
    private void saveRobotCmd(Long merId, Long activityId, String key, List<String> commandList){
        try {
            if(commandList != null && commandList.size() > 0){
                Integer now = DateUtil.getNowTime();
                for(int i =0 ; i < commandList.size() ; i++){
                    String val_tmp = commandList.get(i);
                    MdRobotCmd mdRobotCmd = mdRobotCmdMapper.selectByMerIdAndVal(merId, val_tmp);
                    if(mdRobotCmd != null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "指令已经存在");
                    }else{
                        mdRobotCmd = new MdRobotCmd();
                        mdRobotCmd.setId(IdWorker.getId());
                        mdRobotCmd.setMerId(merId);
                        mdRobotCmd.setActivityId(activityId);
                        mdRobotCmd.setKey(key);
                        mdRobotCmd.setVal(val_tmp);
                        mdRobotCmd.setCreateTime(now);
                        mdRobotCmd.setUpdateTime(now);
                        mdRobotCmdMapper.insert(mdRobotCmd);
                    }
                }
            }
        }catch (Exception e){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }
    }

}
